from nicegui import ui
import os
import json
from pathlib import Path
from src.database.data_chuli import read_excel_data, refresh_database

from src.utils.loggers import app_init_logger

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from src.app import APP


class Content_Upload:

    class Data_Storage:
        '''
            保存当前页面的数据
        '''
        pass

    def __init__(self, container, app: 'APP') -> None:
        self.container = container
        self.APP: 'APP' = app

    def create_upload_content(self):
        with self.container:
            with ui.card().classes('full-width'):
                with ui.card_section():
                    ui.label('支持上传的文件类型：.xlsx, .xls, .xlsm')
                    ui.label('请输入密码')
                    self.password_input = ui.input('请输入密码', password=True)

                with ui.card_section().classes('q-pa-md'):

                    with ui.upload(on_upload=self.handle_upload).classes('full-width'):

                        ui.button('点击上传', icon='upload')

    def handle_upload(self, e):
        """处理上传文件"""
        ui.notify(f'上传文件: {e.name}')
        app_init_logger.info(f'上传文件: {e.name}')

        # 1. 文件类型验证
        allowed_extensions = {'.xlsx', '.xls', '.xlsm'}
        file_ext = os.path.splitext(e.name)[1].lower()
        if file_ext not in allowed_extensions:
            ui.notify(
                f'不支持的文件类型: {file_ext}，仅允许{allowed_extensions}', color='negative')
            return
        if 'F06' in e.name:
            chexing = 'F06'
        elif 'C53F' in e.name:
            chexing = 'C53F'
        elif 'C62X' in e.name:
            chexing = 'C62X'
        else:
            # [ ]  未知车型,需要返回错误信息, 上面几个车型要确认是否匹配
            ui.notify(f'未知车型的数据', color='negative')
            return
        app_init_logger.info(f'chexing为: {chexing}')

        try:
            # 2. 读取Excel文件内容
            # 密码验证
            if self.password_input.value != 'gyz':
                ui.notify('密码错误', color='negative')
                return

            src_Dir = Path(__file__).resolve().parent.parent
            save_dir = src_Dir / "static/" / 'data_temp/'
            app_init_logger.info(f'save_dir为: {save_dir}')

            if not save_dir.exists():
                save_dir.mkdir(parents=False)

            # file_path = os.path.join(save_dir, f'data_{chexing}{file_ext}')
            file_path = save_dir / f'data_{chexing}{file_ext}'
            app_init_logger.info(f'file_path为: {file_path}')

            with open(file_path, 'wb') as f:
                f.write(e.content.read())

            # 3. 数据验证（示例：检查必要列是否存在）
            pass
            df, columnVinDict = read_excel_data()
            print(columnVinDict)
            refresh_database(df, chexing)

            columnVinDictJsonFile = f'columnVinDict_{chexing}.json'
            print('columnVinDictJsonFile', columnVinDictJsonFile)
            with open(os.path.join(src_Dir, "static/", columnVinDictJsonFile), 'w') as f:
                json.dump(columnVinDict, f, ensure_ascii=False, indent=4)

            # 4. 数据处理与存储
            # 示例1：存储原始数据到应用全局存储
            pass

            # 示例2：提取VIN列并更新到查询分析模块

            # 5. 成功反馈
            ui.notify(f'文件处理成功: {e.name} (共{len(df)}条记录)', color='positive')

        except Exception as ex:
            # 6. 错误处理
            error_msg = f'文件处理失败: {str(ex)}'
            ui.notify(error_msg, color='negative')
        finally:
            e.content.close()
